package udp_socket

import (
	"cn.bytengine/stem/events"
	"cn.bytengine/stem/services/app_events"
	"fmt"
	"github.com/panjf2000/gnet/v2"
	"net"
)

type EchoServer struct {
	*gnet.BuiltinEventEngine
}

func (server *EchoServer) OnBoot(engine gnet.Engine) (action gnet.Action) {
	action = gnet.None
	events.Publish(app_events.UdpServerBoot, &UdpServerBootEvent{
		EventObject: &events.EventObject[*EchoServer]{
			EventName: app_events.UdpServerBoot,
			Source:    server,
		},
	})
	return
}

func (server *EchoServer) OnTraffic(c gnet.Conn) (action gnet.Action) {
	var (
		err               error
		buf               []byte
		bufLen            int
		inboundBufferSize int
		remoteAddr        net.Addr
		socket            = c.Fd()
	)
	inboundBufferSize = c.InboundBuffered()
	remoteAddr = c.RemoteAddr()
	fmt.Printf("[INFO] Read data from '%s', the data size: %d\n", remoteAddr.String(), inboundBufferSize)
	action = gnet.None
	buf, err = c.Peek(-1)
	if err != nil {
		fmt.Printf("[ERROR] Read data from '%d' request occurred error. %+v\n", socket, err)
		return
	}
	bufLen = len(buf)
	fmt.Printf("[INFO] Read data from '%d' request: %s, buf size: %d\n", socket, string(buf), bufLen)
	action = gnet.Close
	return
}

func (server *EchoServer) OnClose(c gnet.Conn, err error) (action gnet.Action) {
	var (
		remoteAddr net.Addr
		socket     = c.Fd()
	)
	action = gnet.None
	fmt.Printf("[INFO] Close connect from '%s', the socket handler: %d\n", remoteAddr.String(), socket)
	return
}
